//
//  RequestTool.m
//  Slice
//
//  Created by lanou on 16/6/14.
//  Copyright © 2016年 wangjinchao. All rights reserved.
//

#import "RequestTool.h"

@implementation RequestTool

//数据请求 type请求的类型 urlString网址字符串 parameter参数 callBack返回参数
+ (void)requsetWithType:(requsetType)type URLString:(NSString *)urlString paremeter:(NSDictionary *)parameter callBack:(void(^)(NSData *data, NSError *error))callBack {
// 得到url
    NSURL *url = [NSURL URLWithString:urlString];
//    如果网址中包含中文或其他特殊字符 ,需转换后使用
    if (url == nil) {
        NSString *str = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
        url = [NSURL URLWithString:str];
    }
    
//创建一个可变的请求对象
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    if (type == POST) {
//修改请求的方法
        [request setHTTPMethod:@"POST"];
//    设置请求参数
        if (parameter == nil) {
            NSLog(@"参数未设置");
        } else {
            
        [request setHTTPBody:[RequestTool dataForDic:parameter]];
            
        }
    }
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        回调自己的block 将数据传输出去
        callBack(data,error);
    }];
    [task resume];

}
//将字典转换为data
+(NSData *)dataForDic:(NSDictionary *)dic {
    NSArray *keyArr = [dic allKeys];
    NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0];
    for (id key in keyArr) {
        id value = dic[key];
      NSString  *value1 = (NSString *)value;
        NSString  *key1 = (NSString *)key;
        NSString *one = [NSString stringWithFormat:@"%@=%@",key1,value1];
        [arr addObject:one];
    }
    NSArray *arr1 = (NSArray *)arr;
    NSString *needString = [arr1 componentsJoinedByString:@"&"];
    return [needString dataUsingEncoding:NSUTF8StringEncoding];
}





@end
